sap.ui.define([
    "sap/m/bbf41/Module/controller/BaseController",
    "sap/ui/model/json/JSONModel"
], function (BaseController, JSONModel) {
    "use strict";
    var routeName,
        oView,
        dp,
        oModel = new JSONModel(),
        sSelectedDate,
        uriParamDate;
    return BaseController.extend("sap.m.bbf41.Module.controller.Machining", {
        onInit: function () {
            var me = this;
            oView = me.getView();
            me.handleRefresh();
            oView.byId('Shift1').setHeaderSpan([2]);
            oView.byId('Shift2').setHeaderSpan([2]);
            oView.byId('Shift3').setHeaderSpan([2]);
            var oRouter = this.getRouter();
            oRouter.attachRouteMatched(function (oEvent) {
                routeName = oEvent.getParameter('name').toUpperCase();
                if (routeName == 'G6' || routeName == 'Z6') {
                    me.loadMachiningDataModel();
                }
            });
            dp = oView.byId('historyDatePicker');
            dp.attachEvent('change', function (oEvent) {
                sSelectedDate = oEvent.getSource().getValue();
                var ptn = new RegExp('\-', 'g');
                uriParamDate = sSelectedDate.replace(ptn, '');
                me.handleRefresh();
            });
            var oIconTabBar = oView.byId('IconTabBar');
            oIconTabBar.attachSelect(function () {
                me.handleRefresh();
            });
        },
        handlePressOpenMenu: function (oEvent) {
            var oButton = oEvent.getSource();
            // create menu only once
            if (!this._menu) {
                this._menu = sap.ui.xmlfragment(
                    "sap.m.bbf41.Module.fragment.Machining",
                    this
                );
                this.getView().addDependent(this._menu);
            }
            var eDock = sap.ui.core.Popup.Dock;
            this._menu.open(this._bKeyboard, oButton, eDock.BeginTop, eDock.BeginBottom, oButton);
        },
        handleRefresh: function () {
            this.loadMachiningDataModel();
        },
        loadMachiningDataModel: function () {
            var me = this,
                oShift1Table = oView.byId('shift1Table'),
                oShift2Table = oView.byId('shift2Table'),
                oShift3Table = oView.byId('shift3Table'),
                oMessageStrip = oView.byId('messageStrip'),
                url = '/NEP/PSS/api/product_info?line_name=' + routeName + '&time='+Date.now();
            if (uriParamDate) {
                url += '&date=' + uriParamDate;
            }
            oShift1Table.setBusy(true);
            oShift2Table.setBusy(true);
            oShift3Table.setBusy(true);
            oMessageStrip.setBusy(true);
            setTimeout(function () {
                jQuery.ajax({
                    url: url,
                    dataType: "json",
                    success: function (resp) {
                        var oData = me.buildTableData(resp);
                        oModel.setData(oData);
                        oModel.refresh(true);
                        oView.setModel(oModel);
                        if (routeName == 'G6') {
                            oView.byId('page').setTitle('G6 - Crankcase');
                        }
                        else {
                            oView.byId('page').setTitle('Z6 - Cylinder Head');
                        }
                        oShift1Table.setBusy(false);
                        oShift2Table.setBusy(false);
                        oShift3Table.setBusy(false);
                        oMessageStrip.setBusy(false);
                    }.bind(this),
                    error: function () {
                        oShift1Table.setBusy(false);
                        oShift2Table.setBusy(false);
                        oShift3Table.setBusy(false);
                        oMessageStrip.setBusy(false);
                        jQuery.sap.log.error("failed to load json");
                    }
                });
            }, 768);
        },
        onNavButtonPress: function () {
            this.getRouter().navTo('welcome');
        },
        handleMenuItemPress: function (oEvent) {
            var oMenuItem = oEvent.getSource(),
                routeName = oMenuItem.data('area');
            this.getRouter().navTo(routeName);
        },
        handleDatePicker: function () {
            dp.$().find('.sapUiIcon').trigger('click');
        },
        buildTableData: function (resp) {
            var data = {
                    "Collection": [
                        {
                            "Type": "",
                            "Shift1Input": "Input",
                            "Shift1Output": "Output",
                            "Shift2Input": "Input",
                            "Shift2Output": "Output",
                            "Shift3Input": "Input",
                            "Shift3Output": "Output"
                        },
                        {
                            "Type": "Target",
                            "Shift1Input": "-",
                            "Shift1Output": "-",
                            "Shift2Input": "-",
                            "Shift2Output": "-",
                            "Shift3Input": "-",
                            "Shift3Output": "-"
                        },
                        {
                            "Type": "Current",
                            "Shift1Input": "-",
                            "Shift1Output": "-",
                            "Shift2Input": "-",
                            "Shift2Output": "-",
                            "Shift3Input": "-",
                            "Shift3Output": "-"
                        },
                        {
                            "Type": "Forecast",
                            "Shift1Input": "-",
                            "Shift1Output": "-",
                            "Shift2Input": "-",
                            "Shift2Output": "-",
                            "Shift3Input": "-",
                            "Shift3Output": "-"
                        },
                        {
                            "Type": "Planned",
                            "Shift1Input": "-",
                            "Shift1Output": "-",
                            "Shift2Input": "-",
                            "Shift2Output": "-",
                            "Shift3Input": "-",
                            "Shift3Output": "-"
                        },
                        {
                            "Type": "Deviation",
                            "Shift1Input": "-",
                            "Shift1Output": "-",
                            "Shift2Input": "-",
                            "Shift2Output": "-",
                            "Shift3Input": "-",
                            "Shift3Output": "-"
                        }
                    ],
                    "Shift1StartTime": "-",
                    "Shift1EndTime": "-",
                    "Shift2StartTime": "-",
                    "Shift2EndTime": "-",
                    "Shift3StartTime": "-",
                    "Shift3EndTime": "-",
                    "Shift1": "Shift 1",
                    "Shift2": "Shift 2",
                    "Shift3": "Shift 3",
                    "LineRate": "0",
                    "Date": "yyyy-MM-dd"
                },
                po = data['Collection'],
                setVal = function (v) {
                    return (Math.abs(v) > 0) ? v : '-';
                };
            data['Date'] = sSelectedDate || this.dateHelper(true);
            if (resp) {
                data['Shift1StartTime'] = resp['S1'] || '-';
                data['Shift1EndTime'] = resp['E1'] || '-';
                data['Shift2StartTime'] = resp['S2'] || '-';
                data['Shift2EndTime'] = resp['E2'] || '-';
                data['Shift3StartTime'] = resp['S3'] || '-';
                data['Shift3EndTime'] = resp['E3'] || '-';
                po[1]['Shift1Input'] = setVal(resp['TargetInput1']);
                po[1]['Shift1Output'] = setVal(resp['TargetOutput1']);
                po[1]['Shift2Input'] = setVal(resp['TargetInput2']);
                po[1]['Shift2Output'] = setVal(resp['TargetOutput2']);
                po[1]['Shift3Input'] = setVal(resp['TargetInput3']);
                po[1]['Shift3Output'] = setVal(resp['TargetOutput3']);

                po[2]['Shift1Input'] = setVal(resp['CurrentInput1']);
                po[2]['Shift1Output'] = setVal(resp['CurrentOutput1']);
                po[2]['Shift2Input'] = setVal(resp['CurrentInput2']);
                po[2]['Shift2Output'] = setVal(resp['CurrentOutput2']);
                po[2]['Shift3Input'] = setVal(resp['CurrentInput3']);
                po[2]['Shift3Output'] = setVal(resp['CurrentOutput3']);

                po[2]['Shift1Input'] = setVal(resp['CurrentInput1']);
                po[2]['Shift1Output'] = setVal(resp['CurrentOutput1']);
                po[2]['Shift2Input'] = setVal(resp['CurrentInput2']);
                po[2]['Shift2Output'] = setVal(resp['CurrentOutput2']);
                po[2]['Shift3Input'] = setVal(resp['CurrentInput3']);
                po[2]['Shift3Output'] = setVal(resp['CurrentOutput3']);

                po[3]['Shift1Input'] = setVal(resp['ForecastInput1']);
                po[3]['Shift1Output'] = setVal(resp['ForecastOutput1']);
                po[3]['Shift2Input'] = setVal(resp['ForecastInput2']);
                po[3]['Shift2Output'] = setVal(resp['ForecastOutput2']);
                po[3]['Shift3Input'] = setVal(resp['ForecastInput3']);
                po[3]['Shift3Output'] = setVal(resp['ForecastOutput3']);

                po[4]['Shift1Input'] = setVal(resp['PlannedInput1']);
                po[4]['Shift1Output'] = setVal(resp['PlannedOutput1']);
                po[4]['Shift2Input'] = setVal(resp['PlannedInput2']);
                po[4]['Shift2Output'] = setVal(resp['PlannedOutput2']);
                po[4]['Shift3Input'] = setVal(resp['PlannedInput3']);
                po[4]['Shift3Output'] = setVal(resp['PlannedOutput3']);

                po[5]['Shift1Input'] = (resp['CurrentInput1'] && resp['PlannedInput1']) ? setVal(parseInt(resp['CurrentInput1']) - parseInt(resp['PlannedInput1'])) : '-';
                po[5]['Shift1Output'] = (resp['CurrentOutput1'] && resp['PlannedOutput1']) ? setVal(parseInt(resp['CurrentOutput1']) - parseInt(resp['PlannedOutput1'])) : '-';
                po[5]['Shift2Input'] = (resp['CurrentInput2'] && resp['PlannedInput2']) ? setVal(parseInt(resp['CurrentInput2']) - parseInt(resp['PlannedInput2'])) : '-';
                po[5]['Shift2Output'] = (resp['CurrentOutput2'] && resp['PlannedOutput2']) ? setVal(parseInt(resp['CurrentOutput2']) - parseInt(resp['PlannedOutput2'])) : '-';
                po[5]['Shift3Input'] = (resp['CurrentInput3'] && resp['PlannedInput3']) ? setVal(parseInt(resp['CurrentInput3']) - parseInt(resp['PlannedInput3'])) : '-';
                po[5]['Shift3Output'] = (resp['CurrentOutput3'] && resp['PlannedOutput3']) ? setVal(parseInt(resp['CurrentOutput3']) - parseInt(resp['PlannedOutput3'])) : '-';
                this.calcLineRate(data);
            }
            return data;
        },
        dateHelper: function (oConfig, fixed) {
            var date = new Date(),
                yyyy = date.getFullYear(),
                m = date.getMonth();
            if (fixed === undefined) {
                m += 1;
            }
            var d = date.getDate(),
                paddingNum = function (n) {
                    if (n < 10) {
                        n = '0' + n;
                    }
                    return n;
                },
                MM = paddingNum(m),
                dd = paddingNum(d);
            var result = {
                yyyy: yyyy,
                MM: MM,
                dd: dd
            };
            if (oConfig) {
                var symbol = oConfig['symbol'] || '-';
                result = yyyy + symbol + MM + symbol + dd;
            }
            return result;
        },
        calcLineRate: function (data) {
            var sTodayDateFormatted = this.dateHelper({symbol: '/'}),
                sTodayDate = this.dateHelper(true),
                rate = 0;
            var forceSum = function () {
                    var tv = 2;
                    $.each(arguments, function (k, v) {
                        v = parseInt(v);
                        tv += v || 0;
                    });
                    return tv;
                }, po = data['Collection'],
                dayTotal = forceSum(po[2]['Shift1Output'], po[2]['Shift2Output'], po[2]['Shift3Output']);
            if (!sSelectedDate) {
                sSelectedDate = sTodayDate;
            }
            if (sTodayDate == sSelectedDate) {
                var ds = sTodayDateFormatted + ' ' + data['Shift1StartTime'] + ':00',
                    ts = (new Date(ds)).getTime() / 1000,
                    nts = parseInt((new Date()).getTime() / 1000),
                    nh = parseInt((nts - ts) / 360) / 10;
                rate = nh != 0 ? parseInt(dayTotal * 100 / nh) / 100 : 0;
            }
            else {
                var rPattern = new RegExp('\-', 'g'),
                    sSelectedDateFormatted = sSelectedDate.replace(rPattern, '/'),
                    ds = sSelectedDateFormatted + ' ' + data['Shift1StartTime'] + ':00',
                    ts = (new Date(ds)).getTime() / 1000;
                var vaildShiftGroup;

                if (data['Shift3EndTime'].length > 1) {
                    vaildShiftGroup = [data['Shift3StartTime'], data['Shift3EndTime']];
                }
                else if (data['Shift2EndTime'].length > 1) {
                    vaildShiftGroup = [data['Shift2StartTime'], data['Shift2EndTime']];
                }
                else if (data['Shift1EndTime'].length > 1) {
                    vaildShiftGroup = [data['Shift1StartTime'], data['Shift1EndTime']];
                }

                if (vaildShiftGroup) {
                    var iStartTime = parseInt(vaildShiftGroup[0]),
                        iEndTime = parseInt(vaildShiftGroup[1]),
                        es = sSelectedDateFormatted + ' ' + vaildShiftGroup[1] + ':00',
                        nts = parseInt((new Date(es)).getTime() / 1000);
                    if (iEndTime < iStartTime) {
                        nts += 24 * 3600;
                    }
                    var nh = parseInt((nts - ts) / 360) / 10;
                    rate = nh != 0 ? parseInt(dayTotal * 100 / nh) / 100 : 0;
                }
            }
            data['LineRate'] = rate + ' U/H';
        }
    });

});
